/**
 * 把传入的参数转换为语句
 * @param {string} tName 表名
 * @param {object} where 限制条件
 * @param {string} fields 字段
 */
function toWhere(tName, where = {}, fields = '*') {
    let osql = `SELECT ${fields} FROM  ${tName}`
    if (where.length < 1) {
        return [osql, []]
    }
    let sql = ''
    let params = []
    for (let prop in where) {
        if (where[prop].length > 0) {
            sql += 'and ' + prop + ' in (?) '
            params.push(where[prop])
        }
    }
    if (sql) {
        sql = osql + ' WHERE ' + sql.slice(3)
        return [sql, params]
    } else {
        return [osql, []]
    }
}

const db = require('../db')
/**
 * 分页功能
 * @param {string} sql 查询语句
 * @param {int} page 
 * @param {int} limit 
 */
function dbLimitPage(sql, page = 1, limit = 10) {
    return new Promise((resolve, reject) => {
        if (sql) {
            let countSql = sql.replace(/(?<=select\b).*?(?=\bfrom)/i, ' count(*) ');
            // console.log('countSql', countSql)
            // let result = await db.querySync(countSql, {});
            // let totalCount = result[0]['count(*)'];
            // let list = await db.query(sql, {});
            // return {
            //     currPage: page,
            //     pageSize: limit,
            //     list,
            //     totalCount,
            //     totalPage: Math.ceil(totalCount / limit)
            // }
            db.query(countSql, {}, result => {
                let totalCount = result[0]['count(*)'];
                db.query(sql, {}, list => {
                    resolve({
                        currPage: page,
                        pageSize: limit,
                        list,
                        totalCount,
                        totalPage: Math.ceil(totalCount / limit)
                    })
                })
            })
        } else {
            reject('error')
        }
    })
}
/**
 * 日期转换为年月日
 * @param {*} time 
 * @param {*} splitSrt 
 */
function dateFormatYMD(time = new Date(), splitSrt = '-') {
    var date = new Date(time)
    var Y = date.getFullYear();
    var M = date.getMonth() + 1;
    var D = date.getDate();
    return Y + splitSrt + zeroize(M) + splitSrt + zeroize(D)
}
/**
 * 日期转换为时分秒
 * @param {*} time 
 * @param {*} splitSrt 
 */
function timeFormatHSM(time = new Date(), splitSrt = ':') {
    var date = new Date(time)
    var H = date.getHours();
    var M = date.getMinutes();
    var S = date.getSeconds();
    return zeroize(H) + splitSrt + zeroize(M) + splitSrt + zeroize(S);
}
/**
 * 补零
 * @param {*} num 
 */
function zeroize(num) {
    if (num !== '' && ('' + num).length < 2) {
        return '0' + num;
    }
    return num;
}

/**
 * 把日期转换为 年月日 时分秒
 * @param {Date} date 
 * @param {String} splitYMD 
 * @param {String} splitHSM 
 * @param {String} split 
 */
function dateFormatYMD_HSM(date, splitYMD, splitHSM, split = " ") {
    return dateFormatYMD(date, splitYMD) + split + timeFormatHSM(date, splitHSM)
}

/**
app.set('trust proxy', true);// 设置以后，req.ips是ip数组；如果未经过代理，则为[]. 若不设置，则req.ips恒为[]
app.get('/ip', function(req, res){
  console.log("x-forwarded-for    = " + req.header('x-forwarded-for'));// 各阶段ip的CSV, 最左侧的是原始ip
  console.log("ips                          = " + JSON.stringify(req.ips));// 相当于(req.header('x-forwarded-for') || '').split(',')
  console.log("remote Address     = " + req.connection.remoteAddress);// 未发生代理时，请求的ip
  console.log("ip                            = " + req.ip);// 同req.connection.remoteAddress, 但是格式要好一些
  res.send('Hello World');
});

 */

// app.set('trust proxy', true);// 设置以后，req.ips是ip数组；如果未经过代理，则为[]. 若不设置，则req.ips恒为[]


/**
 * 得到请求的IP
 * 无需设置`app.set('trust proxy', true);`
 * @param {*} req 请求
 */
function getReqRemoteIp(req){return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip;};
module.exports = {
    toWhere,
    dbLimitPage,
    dateFormatYMD_HSM,
    getReqRemoteIp
}
